package com.xt.service.impl;

import com.xt.bean.Module;
import com.xt.bean.Role;
import com.xt.dao.ModuleRepository;
import com.xt.service.ModuleService;
import com.xt.service.RoleService;
import com.xt.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by XT on 2018/5/3.
 */
@Service
public class ModuleServiceImpl implements ModuleService {

    @Autowired
    private ModuleRepository mr;

    @Autowired
    private RoleService rs;

    @Override
    public void deleteModule(String moduleid) {
        Module module = mr.findOne(moduleid);
        String[] roleIds = module.getRoleIds();
        //删除user里面的角色信息
        for (String roleid : roleIds){
            Role role = rs.getRoleById(roleid);
            List<String> moduleIdList = Arrays.asList(role.getModuleIds());
            moduleIdList.remove(moduleid);
            String[] newModuleIds = (String[]) moduleIdList.toArray();
            module.setRoleIds(newModuleIds);
            rs.saveOrUpdateRole(role);
        }

        mr.delete(moduleid);
    }

    @Override
    public void saveOrUpdateModule(Module module) {
        if (StringUtils.isEmpty(module.getId())){
            //新增
            module.setCreateDate(new Date());
        }
        module.setUpdateDate(new Date());
        mr.save(module);
    }

    @Override
    public Module getModuleById(String id) {
        return mr.findOne(id);
    }

    @Override
    public Page<Module> getAllModuleListByPage(int count, int pageNo, String sortDirection, String... sortField) {
        Page<Module> modulesPage = mr.findAll(PageUtil.getPageable(count,pageNo,sortDirection,sortField));
        return modulesPage;
    }
}
